package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.RedisConstants.LOGIN_CODE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 商品类型缓存层
 * @since 2025-08-20
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

   @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String key = CACHE_SHOP_TYPE_KEY;

        // 1. 从 Redis 查询缓存
        List<String> shopTypeJsonList = stringRedisTemplate.opsForList().range(key, 0, -1);

        // 2. 缓存命中，直接返回
        if (CollectionUtil.isNotEmpty(shopTypeJsonList)) {
            List<ShopType> shopTypes = shopTypeJsonList.stream()
                    .map(json -> JSONUtil.toBean(json, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(shopTypes);
        }
        // 3. 缓存未命中，查数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        // 4. 数据不存在
        if (CollectionUtil.isEmpty(shopTypes)) {
            return Result.fail("商铺类型不存在");
        }

        // 5. 写入 Redis 缓存（保持顺序）
        List<String> jsonStrList = shopTypes.stream()
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key, jsonStrList);

        // 6. 可选：设置过期时间（防止永久脏数据）
        stringRedisTemplate.expire(key,30, TimeUnit.MINUTES);

        // 7. 返回结果
        return Result.ok(shopTypes);
    }
}